package com.xuecheng.media.api;

import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.base.model.RestResponse;
import com.xuecheng.media.model.dto.QueryMediaParamsDto;
import com.xuecheng.media.model.po.MediaFiles;
import com.xuecheng.media.service.MediaFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@Api("媒资管理相关接口")
@RestController
public class MediaFileController {
    @Autowired
    MediaFileService mediaFileService;

    @ApiOperation("上传文件接口")
    @PostMapping(value = "/upload/coursefile",
        consumes= MediaType.MULTIPART_FORM_DATA_VALUE)
    public MediaFiles upload(@RequestParam("filedata") MultipartFile filedata,
    @RequestParam(value="objectName",required=false) String objectName){
        Long companyId = 1232141425L;
        return mediaFileService.upload(companyId,filedata,objectName);
    }

    @ApiOperation("媒资管理分页查询接口")
    @PostMapping("/files")
    public PageResult<MediaFiles> page(PageParams pageParams,
            @RequestBody QueryMediaParamsDto paramsDto){
        Long companyId = 1232141425L;
        return mediaFileService.page(companyId,pageParams,paramsDto);
    }

    @ApiOperation("媒资文件预览接口")
    @GetMapping("/preview/{id}")
    public RestResponse<String> preview(@PathVariable Long id){
        Long companyId = 1232141425L;
        MediaFiles mediaFiles = mediaFileService.getById(id);
        if(mediaFiles == null){
            return RestResponse.validfail("找不到该视频");
        }
        if(!companyId.equals(mediaFiles.getCompanyId())){
            XueChengPlusException.cast("当前媒资文件不属于本机构，无权操作");
        }
        if(mediaFiles.getUrl() == null){
            return RestResponse.validfail("该视频正在处理中");
        }
        return RestResponse.success(mediaFiles.getUrl());
    }

    @ApiOperation("移除媒资文件接口")
    @DeleteMapping("/{id}")
    public RestResponse<String> deleteById(@PathVariable Long id){
        Long companyId = 1232141425L;
        return mediaFileService.deleteById(companyId,id);
    }

    @ApiOperation("根据id获取媒资文件")
    @GetMapping("/{id}")
    public MediaFiles getById(@PathVariable Long id){
        Long companyId = 1232141425L;
        MediaFiles mediaFiles = mediaFileService.getById(id);
        if(mediaFiles == null)  return null;
        if(!mediaFiles.getCompanyId().equals(companyId)){
            XueChengPlusException.cast("当前媒资文件不属于本机构，无权操作");
        }
        return mediaFiles;
    }
}
